<?php
/**
 * 用户相关接口
 * @author:wjm
 */

class UserController extends AjaxController {
    /**
     * 用户登录
     * @param username 用户名
     * @param password 密码
     */
    public function login()
    {
        $username = getParam('username', "");
        $password = getParam('password', "");

        // 检查请求参数
        if ($username == '' || $password == '') {
            $this->_data['status'] = self::STATUS_PARAMS_ERROR;
            return $this->echoJson();
        }

        // 检查账号信息
        $status = 0;
        $userId = D('User')->checkLogin($username, $password);
        if ($userId <= 0) {
            if ($userId == -1) {
                $this->_data['status'] = self::STATUS_USERNAME_ERROR;
                $this->_data['errmsg'] = "用户不存在";
            } else if ($userId == -2) {
                $this->_data['status'] = self::STATUS_USERPWD_ERROR;
            } else {
                $this->_data['status'] = self::STATUS_SYSTEM_ERROR;
            }
            return $this->echoJson();
        }

        $now = time();
        $userInfo = D('User')->getSelfInfo($userId);
        $access_token = D('User')->tokenEncode($userInfo['id'], $userInfo['name'], $now + C('ACCESS_TOKEN_EXPIRE'));
        $refresh_token = D('User')->tokenEncode($userInfo['id'], $userInfo['name'], $now + C('REFRESH_TOKEN_EXPIRE'));
        $token_ret = D('UserToken')->addUserToken($userInfo['id'], $access_token, $refresh_token, 1, get_client_ip(0, true));
        if ($token_ret < 0) {
            $this->_data['status'] = self::STATUS_SYSTEM_ERROR;
            return $this->echoJson();
        }
        $this->_data['access_token'] = $access_token;
        $this->_data['refresh_token'] = $refresh_token;
        $this->_data['user'] = $userInfo;
        $this->echoJson();
    }

    public function logout()
    {
        // 获取access_token变量
        $token = getParam("access_token");
        if ($token == '') {
            $this->_data['status'] = self::STATUS_PARAMS_ERROR;
            return $this->echoJson();
        }
        // 修改user_token表中对应记录的status，设置成2表示退出
        $update = D('UserToken')->logoutUpdateStatus($token);
        // 返回正确json
        return $this->echoJson();
    }

    /**
     * 创建用户
     * @param username 用户名
     * @param password 密码
     * @param name 真实姓名
     * @param telephone 电话
     * @param type 用户身份。1认证人，2审核人，3采集人，4公安机关人员
     * @param mechanism_id 所属机构id
     */
    public function createUser() {
        $name = strval(getParam('name',''));
        $username = trim(strval(getParam('username', "")));
        $password = trim(strval(getParam('password', "111111")));
        $telephone = intval(getParam('telephone', 0));
        $type = intval(getParam('type', 0));

        if (strlen($name ) == 0 || strlen($username) <= 0 || strlen($password) <= 0 || $telephone == 0 || $type == 0 ) {
            $this->_data['status'] = self::STATUS_PARAMS_ERROR;
            return $this->echoJson();
        }

        $data['name'] = $name;
        $data['username'] = $username;
        $data['password'] = $password;
        $data['telephone'] = $telephone;
        $data['type'] = $type;
        $user_id = D('User')->addUser($data);
        if ($user_id <= 0) {
            $this->_data['status'] = self::STATUS_USERNAME_EXIST;
            return $this->echoJson();
        }
        $this->_data['id'] = $user_id;
        $this->echoJson();
    }

    /**
     * 删除用户
     * @param user_id
     */
    public function delUser() {
        // 获取user_id参数，如果没有传user_id参数，返回参数异常
        $user_id = intval(getParam("user_id", 0));
        if ($user_id == 0) {
            $this->_data['status'] = self::STATUS_PARAMS_ERROR;
            return $this->echoJson();
        }

        // 判断调用者是不是管理员，如果不是，返回权限异常
        //$role = D('User')->getRoleId('admin');
        if ($this->_user['type'] != 5) {
            $this->_data['status'] = self::STATUS_PERMISSIONS_ERROR;
            return $this->echoJson();
        }
        // 删除用户表中id=user_id用户
        $ret = D('User')->delDataByField(array('id' => $user_id));
        if ($ret === false) {
            $this->_data['status'] = self::STATUS_OPERATION_FAILED;
        }
        $ret = D('User')->delDataByField(array('id' => $user_id));

        // 返回json
        $this->echoJson();
    }

    /**
     * 更新密码
     */
    public function updatePassword()
    {
        $id = intval(getParam('id', $this->_user['id']));
        $password = getParam('password', "111111");
        $origin_pwd = getParam('origin_pwd', "");

        if ($origin_pwd != "") {
            $check = D('User')->checkPassword($id, $origin_pwd);
            if (!$check) {
                $this->_data['status'] = self::STATUS_USERPWD_ERROR;
                return $this->echoJson();
            }
        }
        $status = 0;
        $res = D('User')->forceResetPwd($id, $password, $status);
        if (!$res) {
            $this->_data['status'] = self::STATUS_OPERATION_FAILED;
            return $this->echoJson();
        }
        $this->echoJson();
    }


    /**
     * 重置机构下的人员密码
     */
    public function updateMechanismPassword()
    {
        $id = intval(getParam('mechanism_id',0));
        $password = getParam('password', "111111");
        $status = 0;

        $data = D('User')->getDataByField(array('mechanism_id'=>$id));

        $res = D('User')->forceResetPwd($data[0]['id'], $password, $status);
        if (!$res) {
            $this->_data['status'] = self::STATUS_OPERATION_FAILED;
            return $this->echoJson();
        }
        $this->echoJson();
    }

    /**
     * 获取人员数据
     * @param user_id
     */
    public function getUserDetail() {
        $user_id = intval(getParam('user_id',0));
        $type = intval(getParam('type',0));

        if ($user_id == 0 || $type == 0) {
            $this->_data['status'] = self::STATUS_PARAMS_ERROR;
            return $this->echoJson();
        }
        $data = D('user')->getdataByPk($user_id);
        if ($type == 3) {
            $user_collection_sql = "select * from __TABLE__ where user_id={$user_id}";
            $user_collections = D('UserCollection')->query($user_collection_sql);
            $user_collection = $user_collections[0]['collection_id'];
            $user_collection_name = D('Type')->getdataByPk($user_collection);
            $data['collection_name'] = $user_collection_name['name'];
        }
        $this->_data['data'] = $data;
        $this->echoJson();
    }
    /**
     * 获取自己数据
     * @param user_id
   */
    public function getselfDetail() {
        $user_id  = $this->_user['id'];
        $type = intval(getParam('type',0));

        if ($user_id == 0) {
            $this->_data['status'] = self::STATUS_PARAMS_ERROR;
            return $this->echoJson();
        }
        $data = D('user')->getdataByPk($user_id);
        /*if ($data['type'] == 3) {
            $user_collection_sql = "select * from __TABLE__ where user_id={$user_id}";
            $user_collections = D('UserCollection')->query($user_collection_sql);
            $user_collection = $user_collections[0]['collection_id'];
            $user_collection_name = D('Type')->getdataByPk($user_collection);
            $data['collection_name'] = $user_collection_name['name'];
        }*/
        $this->_data['data'] = $data;
        $this->echoJson();
    }

    /**
 * 更新采集人员的数据
 * @param user_id
 */
    public function updataCollectionUser() {
        $username = strval(getParam('username', ""));
        $name = strval(getParam('name', ""));
        $telephone = intval(getParam('telephone', 0));
        $email = strval(getParam('email', 0));
        $collection_id = intval(getParam('collection_id',0));
        $user_id = intval(getParam('user_id',0));

        if ($user_id == 0) {
            $this->_data['status'] = self::STATUS_PARAMS_ERROR;
            return $this->echoJson();
        }

        $data['id'] = $user_id;
        $data['username'] = $username;
        $data['name'] = $name;
        $data['telephone'] = $telephone;
        $data['email'] = $email;

        $collection['collection_id'] = $collection_id;

        $update_message= D('User')->updateData($data);
        if ($update_message === false) {
            $this->_data['status'] = self::STATUS_OPERATION_FAILED;
            return $this->echoJson();
        }

        $sql = "UPDATE __TABLE__ SET `collection_id` = $collection_id WHERE `user_id` = $user_id";
        $update_message=D('UserCollection')->execute($sql);
        $this->echoJson();
    }

    /**
     * 更新自己数据
     * @param user_id
     */
    public function updataSelfUser() {
        $username = strval(getParam('username', ""));
        $name = strval(getParam('name', ""));
        $telephone = intval(getParam('telephone', 0));
        $email = strval(getParam('email', 0));

        $user_id  = $this->_user['id'];

        $data['id'] = $user_id;
        $data['username'] = $username;
        $data['name'] = $name;
        $data['telephone'] = $telephone;
        $data['email'] = $email;

        $update_message= D('User')->updateData($data);
        if ($update_message === false) {
            $this->_data['status'] = self::STATUS_OPERATION_FAILED;
            return $this->echoJson();
        }

        $this->echoJson();
    }

    /**
     * 对比用户名
     * @param user_id
     */
    public function checkUserName() {
        $user_name = getParam('username','');
        if($user_name == '') {
            $this->_data['status'] = self::STATUS_PARAMS_ERROR;
            return $this->echoJson();
        }

        $bool = D('User')->getDataByField(array('username' => $user_name));
        if(!empty($bool)) {
            $this->_data['status'] = self::STATUS_OPERATION_REPEATED;
            $this->_data['errmsg'] = '该用户名已被注册，请重新输入';
            return $this->echoJson();
        }
        $this->echoJson();
    }

}
